import { _decorator, Component, Node, SpriteFrame } from 'cc';
import { FrameAnim } from '../../moon/ctrl/FrameAnim';
import { CowGame } from '../CowGame';
const { ccclass, property } = _decorator;


@ccclass('CowSkin')
export class CowSkin {

    @property([SpriteFrame])
    cowAnim: SpriteFrame[] = []

}


@ccclass('Cow')
export class Cow extends Component {

    @property([CowSkin])
    cowSkinSet: CowSkin[] = []

    private frameAnim: FrameAnim

    typeIdx: number

    private speedX: number;

    private cowGame: CowGame

    private inited: boolean;

    protected onLoad(): void {
        this.frameAnim = this.node.addComponent(FrameAnim)

        this.typeIdx = Math.floor(Math.random() * 3)
        if (this.typeIdx >= 4) {
            this.typeIdx = 3;
        }
        this.playWalk()
        this.speedX = - (Math.random() * 200 + 200)
    }

    init(cowGame: CowGame) {
        this.cowGame = cowGame;
        this.inited = true;
    }


    playWalk() {
        this.frameAnim.spriteFrames = this.cowSkinSet[this.typeIdx].cowAnim;
        this.frameAnim.duration = 0.2;
        this.frameAnim.playLoop();
    }

    update(deltaTime: number) {
        if(!this.inited){
            return;
        }
        let position = this.node.getPosition()
        let newPos = position.add3f(this.speedX * deltaTime, 0, 0)
        this.node.setPosition(newPos)
        if (newPos.x <= -540) {
            this.cowGame.removeCow(this.node)
            this.node.removeFromParent()
        }
    }
}

